#include <iostream>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>

// CUDA-related headers
#include <cuda_runtime.h>
#include <device_launch_parameters.h>

// CUDA program that runs in the background
__global__ void dummy_kernel() {}

int main(int argc, char** argv) {
    // CUDA initialization
    cudaInit();

    // Define a signal handler for the exit signal
    void signalHandler(int signal) {
        switch (signal) {
            case SIGINT: //捕获SIGINT信号
                std::cerr << "Received signal SIGINT. Closing CUDA daemon...\\n";
                // 释放CUDA资源
                cudaDeviceReset();
                // 退出守护进程
                exit(0);
                break;
            default:
                std::cerr << "Received unknown signal: " << signal << "\\n";
                exit(1);
        }
    }

    // Register signal handler
    signal(SIGINT, signalHandler);

    // Launch the CUDA kernel in an infinite loop
    dummy_kernel<<<1, 1>>>(0);

    // Keep the main thread running to catch signals
    while (true) {
        // Do nothing, just wait for a signal
        wait(NULL);
    }

    return 0;
}
